package com.jin.webvideo.config.filter.access.rule;

import com.jin.webvideo.config.filter.access.GlobalStore;
import com.jin.webvideo.config.filter.access.handler.AccessHandler;
import com.jin.webvideo.entity.SessionStore;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 分支执行规则
 * @author biao532
 * @date 2023/12/05 11:05
 **/
public class BranchAccessRule implements AccessHandler.AccessRule {
    public static final AccessHandler.AccessRule TRUE = (g, s, r) -> true;
    public static final AccessHandler.AccessRule FALSE = AccessHandler.AccessRule.NONE;

    private List<AccessHandler.AccessRule> cases = new ArrayList<>(0);
    private List<AccessHandler.AccessRule> rules = new ArrayList<>(0);
    private AccessHandler.AccessRule defaultRule =  NONE;

    public void setDefault(AccessHandler.AccessRule defaultRule) {
        this.defaultRule = defaultRule;
    }

    public void addCase(AccessHandler.AccessRule caseRule, AccessHandler.AccessRule branch) {
        this.cases.add(caseRule);
        this.rules.add(branch);
    }
    @Override
    public boolean compute(GlobalStore globalStore, SessionStore store, HttpServletRequest request) {
        for (int i = 0, l = cases.size(); i < l; i ++) {
            AccessHandler.AccessRule caseRule = cases.get(i);
            if (caseRule.compute(globalStore, store, request)) {
                return rules.get(i).compute(globalStore, store, request);
            }
        }
        return defaultRule.compute(globalStore, store, request);
    }
}
